package com.david.core.imgloader;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

import com.david.core.imgloader.bean.ImgRequestInfo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class LruImageLoaderUtils {
    /**
     * 获取带后缀的图片名
     * https://pics2.baidu.com/feed/d043ad4bd11373f07cfedf093f1d9bfcfaed0479.jpeg?token=de18eb3030df73681a7ee453fb698651&s=95A742B60A9168CEE4BF9D7A03009018
     * https://img-home.csdnimg.cn/images/20201231031228.jpg
     *
     * @param imageUrl 图片url
     * @return 带后缀的图片名
     */
    public static String getImageName(String imageUrl) {
        if (imageUrl.contains("?")) {//带参数
            imageUrl = imageUrl.substring(0, imageUrl.indexOf("?"));
        }
        return imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
    }


    public static boolean isImgCached(String imgUrl){
        String imageID = LruImageLoaderUtils.getImageName(imgUrl);
        return new File(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imageID).exists();
    }

    public static boolean isImgIdCached(String imgId){
        return new File(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imgId).exists();
    }

    public static InputStream getImgCacheStream(String imgUrl){
        String imageID = LruImageLoaderUtils.getImageName(imgUrl);
        try {
            return new FileInputStream(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imageID);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    //    如果图片比较大可能会导致oom，因此先保存，从文件中读取
    public static byte[] getBytesInputStream(InputStream is) {
        try {
            ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[512];
            int len;
            while ((len = is.read(buff)) != -1) {
                arrayOutputStream.write(buff, 0, len);
            }
            is.close();
            arrayOutputStream.close();
            return arrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**小图时加载到内存并保存*/
    public static void writeToFile(byte[] data, String fileAbsolutePath) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileAbsolutePath);
            outputStream.write(data, 0, data.length);
            outputStream.flush();

            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**从二进制数组中加载图片*/
    public static Bitmap loadImage(byte[] array, int width){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(array, 0, array.length,  options);

        options.inSampleSize = width > 0?options.outWidth / width:2;//默认缩小一倍
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeByteArray(array, 0, array.length,  options);
    }



    /**图片大于300k时先写入文件，防止图片很大导致oom*/
    public static void writeToFile(InputStream is, String fileAbsolutePath) {
        BufferedInputStream bufferedInputStream = null;
        FileOutputStream fileOutputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        try {

            bufferedInputStream = new BufferedInputStream(is);
            fileOutputStream = new FileOutputStream(fileAbsolutePath);
            bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
            byte[] buff = new byte[512];
            int len;
            while ((len = bufferedInputStream.read(buff)) != -1) {
                bufferedOutputStream.write(buff, 0, len);
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**从缓存文件中加载图片*/
    public static Bitmap loadImage(String imageID, int width){
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imageID, options);

        options.inSampleSize = width > 0?options.outWidth / width:2;//默认缩小一倍
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        return BitmapFactory.decodeFile(LruImageLoader.getApplicationContext().getExternalCacheDir() + File.separator + imageID, options);
    }


    public static void setImage(Map<String, ImgRequestInfo> imageViewMap, String imageID, boolean isError, int errorImgId, Bitmap bitmap){
        ImgRequestInfo requestInfo = imageViewMap.remove(imageID);
        if (requestInfo != null) {
            for (ImageView imageView:requestInfo.getImageViews()) {
                if (imageView != null) {
                    if (isError) {
                        if (errorImgId > 0) {
                            imageView.setImageResource(errorImgId);
                        }
                    } else {
                        imageView.setImageBitmap(bitmap);
                    }
                }
            }

            requestInfo.getImageViews().clear();
            requestInfo.setImageViews(null);
            requestInfo.setTag(null);
            requestInfo.setUrl(null);
        }
    }
}
